<template>
  <div class="container">
    <index-head></index-head>
    <div class="main clearfix">
      <div class="breadcrumb_mainBody_tab_tilte innovation_head_tag">
        <index-breadcrumb></index-breadcrumb>
        <div style="display: inline-block">
          <el-tabs v-model="value" type="card" class="innovation_tag_select" @tab-click="legendClick">
            <!-- <el-tab-pane class="timeCheck" label="行业对比图" name="1"></el-tab-pane> -->
            <el-tab-pane class="timeCheck" label="地区对比图" name="2"></el-tab-pane>
            <el-tab-pane class="timeCheck" label="时间趋势图" name="3"></el-tab-pane>
          </el-tabs>
          <div class="mainBody innovation_button_select" ref="imageWrapper">
            <a :href="downImg" :download="picName" id="downImg" style="display: none"></a>
            <ul class="mainBody_tab_tilte clearfix">
              <li @click="output">
                <img src="../assets/image/mainCon_icon2.png" />
                <span>导出</span>
              </li>
              <li @click="print">
                <img src="../assets/image/mainCon_icon3.png" />
                <span>打印</span>
              </li>
              <li @click="downloadImpByChart">
                <img src="../assets/image/mainCon_icon4.png" />
                <span>保存</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="mainPositionWin" v-show="mainPositionWinShow">
        <div class="positionTitle">
          <div class="clearfix">
            <p class="positionTitle_a">条件</p>
            <p class="positionTitle_close" @click="conditionsClose">
              <img src="../assets/image/close.png" />
            </p>
            <p class="positionTitle_clear" @click="conditionsClear">清 空</p>
            <p class="positionTitle_extract" @click="termSubmit">数据提取</p>
          </div>
          <div class="navCntBox clearfix">
            <div class="getIndexBox">
              <span class="titleYellow">指标</span>
              <el-checkbox-group v-model="getCloumns" @change="handleCheckedGetCloumnsChange">
                <el-checkbox v-for="getCloumnsName in getCloumnss" :label="getCloumnsName.key" :key="getCloumnsName.key">
                  {{ getCloumnsName.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <!-- <div class="getIndexBox">
              <span class="titleYellow">行业</span>
              <el-checkbox-group v-model="getIndex" @change="handleCheckedGetIndexChange">
                <el-checkbox v-for="getIndexName in getIndexs" :label="getIndexName.key" :key="getIndexName.key">
                  {{ getIndexName.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div> -->
            <div class="getRegionBox" v-if="isVisibleAreaTab">
              <span class="titleYellow">地区</span>
              <el-checkbox-group v-model="getRegion" @change="handleCheckedGetRegionChange">
                <el-checkbox v-for="item in getRegions" :label="item.key" :key="item.key">{{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="getTimeBox">
              <p class="titleYellow">时间</p>
              <el-checkbox-group v-model="getTime" @change="handleCheckedGetTimeChange">
                <el-checkbox v-for="getTimeName in getTimes" :label="getTimeName.key" :key="getTimeName.key">
                  {{ getTimeName.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </div>
      <div class="mainTerm">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="指标" name="norm">
            <div class="tree">
              <el-tree class="filter-tree" :data="cloumnstree" :props="defaultPropscloumn" :default-expand-all="true" :filter-node-method="filterNodeclounm" ref="treeCloumns" show-checkbox node-key="code" @node-click="nodeClickHandlecloumn" :default-expanded-keys="[]" @check-change="checkCloumns"></el-tree>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="行业" name="first">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterText" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="data" :props="defaultProps" :filter-node-method="filterNode" ref="tree" show-checkbox node-key="codes" @node-click="nodeClickHandle" :default-expanded-keys="[]" @check-change="checkChangeHandle"></el-tree>
            </div>
          </el-tab-pane> -->
          <el-tab-pane label="地区" name="second" class="timeCheck" v-if="isVisibleAreaTab">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextRegion" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextRegionClear" />
            </div>
            <div class="tree">
              <el-tree class="filter-tree" :data="dataRegion" :props="defaultPropsRegion" :default-expand-all="true" :filter-node-method="filterNodeRegion" ref="treeRegion" show-checkbox node-key="code" @node-click="nodeClickHandleRegion" :default-expanded-keys="[]" @check-change="checkChangeHandleRegion">
              </el-tree>
            </div>
          </el-tab-pane>
          <el-tab-pane label="时间" name="three" class="timeCheck">
            <div class="clearfix">
              <el-input placeholder="输入关键字进行过滤" v-model="filterTextTime" class="inputFloat"></el-input>
              <img src="../assets/image/refresh.png" class="imgFloat" @click="filterTextTimeClear" />
            </div>

            <el-dropdown trigger="click" @command="timeFilterSelectFn" style="color: #fff" class="timeSelect">
              <span class="el-dropdown-link">
                {{ timeFilterSelectVal }}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="item" v-for="item in timeFilterSelectArr" :key="item.label">{{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <div class="tree">
              <el-tree class="filter-tree" :data="dataTime" :props="defaultPropsTime" :default-expand-all="true" :filter-node-method="filterNodeTime" ref="treeTime" show-checkbox node-key="id" @node-click="nodeClickHandleTime" :default-expanded-keys="[]" @check-change="checkChangeHandleTime">
              </el-tree>
            </div>
          </el-tab-pane>
        </el-tabs>
        <p @click="termlook" class="conditions">查看条件</p>
      </div>
      <div class="mainContainer">

        <div class="mainBody" ref="imageWrapper">
          <div class="mainBody_tab_content">
            <div>
              <div v-show="anaDataShow">
                <h1 class="anaDataTitle" @click="anaDataTitleBtn">
                  <span>{{ anaDataTitle }}</span>
                  <img src="../assets/image/anaDataTitle.png" />
                  <p class="anaDataClose" @click="anaDataClose">
                    <img src="../assets/image/close.png" />
                  </p>
                </h1>
                <div id="anaData" class="clearfix" v-show="anaDataCnt"></div>
              </div>
              <div class="chartBox clearfix">
                <div id="myChart" :style="{ width: '100%', height: '400px' }" v-show="graphShow"></div>
              </div>
              <!--  指标说明-->
              <div class="predictWinBox indexCodePopBox" v-if="isIndexCodePopShow">
                <div class="predictWin">
                  <div class="predictTitle indexCodePop">
                    指标说明
                    <img src="../assets/image/close.png" @click="isIndexCodePopShow = false" />
                  </div>
                  <ul>
                    <li v-for="(item, index) in macroIndexCodeArr" :key="index">
                      <div>{{ item.name }}</div>
                      <div>{{ item.value }}</div>
                    </li>
                  </ul>
                </div>
              </div>
              <!-- 时间 + 指标  -->
              <div class="table-l emptyLeft">
                <jsonTable :data="tableDataff" id="tableDetailData"  :columns="tabslist">
                  <template #ptKind="{row}">
                    <span v-if="row.ptKind == 'A'">发明专利申请</span>
                    <span v-if="row.ptKind == 'B'">发明专利授权</span>
                    <span v-if="row.ptKind == 'U'">新型专利授权</span>
                    <span v-if="row.ptKind == 'S'">外观设计专利授权</span>
                  </template>
                  <template #tmImgPath="{row}">
                    <el-image v-if="row.tmImgPath !== null" style="width: 30px;" :src="'https://static.shujuquan.com/trademark'+ row.tmImgPath" :preview-src-list="['https://static.shujuquan.com/trademark'+row.tmImgPath]">
                      <div slot="error" class="image-slot">

                      </div>
                    </el-image>
                  </template>
                  <template #ptInsBook="{row}">
                    <el-link v-if="row.ptInsBook" type="primary" :href="'https://static.shujuquan.com/patent' + row.ptInsBook" target="_blank">查看</el-link>
                  </template>
                  <template #tmType="{row}">
                    <span v-if="row.tmType == 'P'">普通商标</span>
                    <span v-if="row.tmType == 'Z'">证明商标</span>
                    <span v-if="row.tmType == 'J'">集体商标</span>
                    <span v-if="row.tmType == 'T'">特殊商标</span>
                  </template>
                </jsonTable>
              </div>
              <div class="flex-center">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[20, 40, 60, 80]" :page-size="limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <com-foot></com-foot>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import indexHead from "../components/head";
import comFoot from "../components/comfoot";
import indexBreadcrumb from "../components/breadcrumb";
import html2canvas from "html2canvas";
import _ from 'lodash';
// import "echarts-map/js/china.js";
import XLSX from "xlsx";
import FileSaver from "file-saver";
import geoCoordMap from "./components/macro/geoCoordMap.js";
import { getHideAreaArr, tabTable } from "./components/macro/table.js";

export default {
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      statisticType: "1",
      sourceData: {}, // 数据接口返回的源码
      activeName: "norm",
      token: localStorage.getItem("TOKEN_KEY"),
      mapYearsNum: 0,
      mainPositionWinShow: false,
      sysannouncementVisible: false,
      isIndexCodePopShow: false,
      statementShow: true,
      analysisWin: false,
      predictWin: false,
      anaDataShow: false,
      anaDataCnt: true,
      other: "",
      legend: [],
      tabslist: [],
      cloumnstree: [],
      industrydata: [],
      getCloumns: [],
      getCloumnss: [],
      getIndex: [],
      getTime: [],
      getTimes: [],
      getIndexs: [],
      checkedStat: [],
      getRegions: [],
      getRegion: [],
      tableYears: [],
      mapYears: [],
      macroIndexCodeArr: [],
      charttitle: {
        text: '2011年 - 2020年企业创新行业对比',
        left: '120',
        top: '20',
        textStyle: {
          color: '#fff'
        },
      },
      tableDataff: [],
      dataRegion: [
        {
          id: 2,
          codename: "全选",
          children: [
            {
              id: 5,
              label: "二级 2-1",
            },
            {
              id: 6,
              label: "二级 2-2",
            },
          ],
        },
      ],
      mapIndex: "",
      filterText: "",
      downImg: "",
      graphShow: true,
      timeFilterSelectArr: [
        {
          value: 5,
          label: "近5年",
        },
        {
          value: 10,
          label: "近10年",
        },
        {
          value: 20,
          label: "近20年",
        },
      ],
      defaultPropsTime: {
        children: "children",
        label: "label",
      },
      defaultPropscloumn: {
        children: "children",
        label: "label",
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      dataTime: [
        {
          id: 3,
          label: "全选",
          children: [],
        },
      ],
      anaDataTitle: "",
      timeFilterSelectVal: "",
      filterTextTime: "",
      filterTextRegion: "",
      picName: "",
      cur: 0,
      value: "1",
      defaultPropsRegion: {
        children: "children",
        label: "codename",
      },
      originalcloumns: []
    }
  },
  components: {
    indexHead,
    comFoot,
    html2canvas,
    indexBreadcrumb
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterTextRegion(val) {
      if (this.isVisibleAreaTab) this.$refs.treeRegion.filter(val);
    },
    filterTextTime(val) {
      this.$refs.treeTime.filter(val);
    },
    $route(to, from) {
      // 防止外部跳入重复执行
      if (to.name === from.name) this.reload();
    },
  },
  computed: {
    ...mapGetters({ userInfo: 'getUserInfo' }),
    // 是否显示 地区 tab
    isVisibleAreaTab() {
      let arr = getHideAreaArr();
      return arr.indexOf(this.tableName) < 0;
    },
    tableName() {
      if (this.$route.query.tablename.indexOf("season") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [
          {
            value: 4,
            label: "前4季度",
          },
          {
            value: 8,
            label: "前8季度",
          },
          {
            value: 12,
            label: "前12季度",
          },
        ];
      else if (this.$route.query.tablename.indexOf("month") != -1)
        //前4/8/12季度
        this.timeFilterSelectArr = [

          {
            value: 12,
            label: "前12月",
          },
          {
            value: 24,
            label: "前24月",
          },
          {
            value: 36,
            label: "前36月",
          },
        ];

      return this.$route.query.tablename || "tech_innovate_month";
    }
  },
  mounted() {
    $(function () {
      $(".el-badge.item sup").hide();
      var url = window.location.href;
      var loc = url.substring(url.lastIndexOf("=") + 1, url.length);
      if (loc == "beltroad_year") {
        $(".mainBody_tab_tilte li").eq(6).hide();
      }
    });
    this.firstInit();
    this.inittable();
    this.statistic();
  },
  methods: {
    lookimg(img) {
      let image = 'https://static.shujuquan.com/trademark' + img.tmImgPath
      this.$previewImg({ src: image });
    },
    paTime(e) {
      if (e == undefined) return
      return this.$dayjs(e).format("YYYY-MM-DD")
    },
    handleCurrentChange(val) {
      this.page = val;
      this.gettable();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.gettable();
    },
    // 过滤数据
    chartformat() {
      let { defaultData, value, getCloumns } = this;
      this.industrydata = []
      var legend = [];
      if (getCloumns.length > 0) {
        _.map(getCloumns, cl => {
          let ovr = cl.substring(0, 4);;
          // if (ovr == '0001') {
          //   legend.push('公司数')
          // } 
          // else if (ovr == '0002') {
          //   legend.push('软著数')
          // } else if (ovr == '0003') {
          //   legend.push('专利数')
          // } else 
          // if (ovr == '0004') {
          //   legend.push('商标数')
          // }

          if (ovr == '0003') {
            legend.push('专利数')
          }
        })
      } else {
        legend = ['专利数']
      }
      this.legend = _.uniq(legend)

      if (value == 2) { // 地区
        let newname = []
        let industrydata = []
        _.map(defaultData, (c, v) => {
          let namearr = []
          _.map(c, (key, index) => {
            namearr.push(index.split("|")[1])
          })
          newname = _.uniq(namearr)
        })
        _.map(newname, (key1, key2) => {
          let obj = {
            name: key1,
            data: []
          }
          industrydata.push(obj)
        })
        _.map(industrydata, (item) => {
          var E001 = [], P001 = [], T001 = [], S001 = []
          _.map(defaultData, (c, ne) => {
            _.map(c, (dz, dv) => {
              _.map(dz, dzt => {
                // if (item.name == dv.split('|')[1] && dzt['E001|公司数'] !== undefined) {
                //   E001.push(dzt['E001|公司数'])
                // }
                if (item.name == dv.split('|')[1] && dzt['P001|专利数'] !== undefined) {
                  P001.push(dzt['P001|专利数'])
                }
                // if (item.name == dv.split('|')[1] && dzt['T001|商标数'] !== undefined) {
                //   T001.push(dzt['T001|商标数'])
                // }
                // if (item.name == dv.split('|')[1] && dzt['S001|软著数'] !== undefined) {
                //   S001.push(dzt['S001|软著数'])
                // }
              })

              item.data = [
                // { 'lable': '公司数', 'value': _.sum(E001) },
                { 'lable': '专利数', 'value': _.sum(P001) },
                // { 'lable': '商标数', 'value': _.sum(T001) },
                // { 'lable': '软著数', 'value': _.sum(S001) },
              ]
            })
          })
        })
        this.industrydata = industrydata
      } else if (value == 3) { // 时间
        let industry = []
        let timearr = []
        let tiem = []
        _.map(defaultData, (v1) => {
          _.map(v1, (v2, v2s) => {
            _.map(v2, (v3, v3s) => {
              tiem.push(v3s)
            })
          })
        })
        timearr = _.uniq(tiem)

        _.map(timearr, key1 => {
          let obj = {
            name: key1,
            data: []
          }
          industry.push(obj)
        })

        _.map(industry, (tm) => {
          var E001 = [], P001 = [], T001 = [], S001 = []
          _.map(defaultData, (c, ne) => {
            _.map(c, (dz, dv) => {
              _.map(dz, dzt => {
                _.map(dz, (dk, dt) => {
                  // if (tm.name == dt && dk['E001|公司数'] !== undefined) {
                  //   E001.push(dk['E001|公司数'])
                  // }
                  if (tm.name == dt && dk['P001|专利数'] !== undefined) {
                    P001.push(dk['P001|专利数'])
                  }
                  // if (tm.name == dt && dk['T001|商标数'] !== undefined) {
                  //   T001.push(dk['T001|商标数'])
                  // }
                  // if (tm.name == dt && dk['S001|软著数'] !== undefined) {
                  //   S001.push(dk['S001|软著数'])
                  // }
                })
                tm.data = [
                  // { 'lable': '公司数', 'value': _.sum(E001) },
                  { 'lable': '专利数', 'value': _.sum(P001) },
                  // { 'lable': '商标数', 'value': _.sum(T001) },
                  // { 'lable': '软著数', 'value': _.sum(S001) },
                ]
              })
            })
          })
        })
        this.industrydata = industry
      }
    },

    filteratetable() {
      this.tableDataff = []
      this.tabslist = []
      let tablelist = []
      this.getCloumns = _.uniq(this.getCloumns)
      tablelist = _.uniq(tablelist)
      _.map(this.originalcloumns, item => {
        _.map(this.getCloumns, iotm => {
          if (iotm == item.code) {
            tablelist.push(item)
          }
        })
      })
      _.map(tablelist, i => {
        // if(i.isShow == 1) {
        this.getCloumns.push(i.code)
        let obj = {
          label: i.fullname,
          prop: i.prop,
          code: i.code,
          width: tablelist.length > 10 ? 200 : ''
        }
        if (i.prop == 'tmImgPath' || i.prop == 'ptKind' || i.prop == 'ptInsBook') {
          obj.useSlot = true
        }
        this.tabslist.push(obj)
        // }
      })
    },

    // 动态获取列表
    dynamiclist() {
      var that = this;
      var Cloumnslog = []
      var params = new URLSearchParams();
      params.append("tableName", that.tableName);
      this.$axios.request({
        url: "5700/websingletable/getCloumns",
        method: "get",
        params: params,
      }).then(function (res) {
        that.originalcloumns = res.data
        _.map(res.data, i => {
          if (i.isShow == 1) {
            Cloumnslog.push(i.code)
            let obj = {
              label: i.fullname,
              prop: i.prop,
              code: i.code,
              width: '200'
            }
            if (i.prop == 'tmImgPath' || i.prop == 'ptKind' || i.prop == 'ptInsBook') {
              obj.useSlot = true
            }
            that.tabslist.push(obj)
          }
        })
        localStorage.setItem('Cloumnslog', JSON.stringify(Cloumnslog))
      })
    },

    firstInit() {
      var that = this;
      let result = tabTable.find((item) => {
        return item.tableName.indexOf(this.tableName) >= 0;
      });
      var params = new URLSearchParams();
      params.append("tableName", that.tableName);
      // // 获取行业
      // let data1 = new Promise((resolve, reject) => {
      //   this.$axios
      //     .request({
      //       url: "5700/websingletable/getIndex",
      //       method: "get",
      //       params: params,
      //     })
      //     .then(function (response) {
      //       var data = that.getNavData(response.data);
      //       that.data = data;
      //       resolve(response);
      //     })
      //     .catch(function (error) {
      //       reject(error);
      //       console.log(error);
      //     });
      // });
      // 获取时间
      let dataTime1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getTechTime",
            method: "get",
            params: params,
          })
          .then(function (res) {
            resolve(res);
            // 原始数据
            res.data.sort(function (a, b) {
              return b - a;
            });
            that.timeSource = res.data;
            if (res.data) {
              that.setTimeTrees(res, result);
            }
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });
      // 获取地区
      let dataRegion1 = new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getRegion",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.setRegionTrees(res, result);
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
            console.log(error);
          });
      });

      // 获取指标
      let dataCloumns = new Promise((resolve, reject) => {
        let self = this;
        this.$axios
          .request({
            url: "5700/websingletable/getCloumns",
            method: "get",
            params: params,
          }).then(function (res) {
            var Cloumnstree = that.getClData(res.data);
            that.cloumnstree = Cloumnstree
            resolve(res);
          }).catch(function (error) {
            reject(error);
          })
      })

      dataTime1.then(() => {
      //   return dataTime1;
      // }).then(() => {
        return dataRegion1;
      }).then(() => {
        return dataCloumns;
      }).then(() => {
        let pageType = this.$route.query.pageType;
        if (pageType === "changeParam") {
          // 自带默认查询数据,从收藏列表页面过来
          let { indexCloumns, regionCode, timeCode } = JSON.parse(
            localStorage.getItem("macroCodes")
          );
          this.checkCloumns(null, null, null, indexCloumns.split(","));
          // this.checkChangeHandle(null, null, null, indexCode.split(","));
          this.checkChangeHandleRegion(null, null, null, regionCode.split(","));
          this.checkChangeHandleTime(null, null, null, timeCode.split(","));
          // todo  从缓存中拿数据
          return this.termSubmit();
        }
        return that.websingletableGetData();
      })
        .finally(() => {
          that.mainPositionWinShow = false;
        });
    },

    // nodeClickHandle(data) {
    //   var checkedKeys = this.$refs.tree.getCheckedKeys();
    //   if (!data.children || data.children.length == 0) {
    //     for (var i = 0; i < this.data.length; i++) {
    //       var data1 = this.data[i];
    //       if (data1.children && data1.children.length) {
    //         if (checkedKeys.indexOf(data1.codes) >= 0) {
    //           checkedKeys.splice(checkedKeys.indexOf(data1.codes), 1);
    //         }
    //         for (var j = 0; j < data1.children.length; j++) {
    //           var data2 = data1.children[j];
    //           if (data2.children && data2.children.length) {
    //             if (checkedKeys.indexOf(data2.codes) >= 0) {
    //               checkedKeys.splice(checkedKeys.indexOf(data2.codes), 1);
    //             }
    //           }
    //         }
    //       }
    //     }
    //     var idx = checkedKeys.indexOf(data.codes);
    //     if (idx < 0) {
    //       checkedKeys.push(data.codes);
    //     } else {
    //       checkedKeys.splice(idx, 1);
    //     }
    //     this.$refs.tree.setCheckedKeys(checkedKeys);
    //   }
    //   this.mainPositionWinShow = true;
    // },

    nodeClickHandlecloumn(data) {
      var checkedKeys = this.$refs.treeCloumns.getCheckedKeys();
      if (!data.children || data.children.length == 0) {
        for (var i = 0; i < this.cloumnstree.length; i++) {
          var data1 = this.cloumnstree[i];
          if (data1.children && data1.children.length) {
            if (checkedKeys.indexOf(data1.code) >= 0) {
              checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
            }
            for (var j = 0; j < data1.children.length; j++) {
              var data2 = data1.children[j];
              if (data2.children && data2.children.length) {
                if (checkedKeys.indexOf(data2.code) >= 0) {
                  checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
                }
              }
            }
          }
        }
        var idx = checkedKeys.indexOf(data.code);
        if (idx < 0) {
          checkedKeys.push(data.code);
        } else {
          checkedKeys.splice(idx, 1);
        }
        this.$refs.treeCloumns.setCheckedKeys(checkedKeys);
      }
      this.mainPositionWinShow = true;
    },

    getClData(list, parentId) {
      if (!parentId) {
        parentId = 0;
      }
      let result = [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].parenid == parentId) {
          list[i].label = list[i].fullname;
          list[i].children = this.getClData(list, list[i].id);
          result.push(list[i]);
        }
      }
      return result;
    },

    getNavData(list, parentId) {
      if (!parentId) {
        parentId = 0;
      }
      let result = [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].parenid == parentId) {
          list[i].label = list[i].fullname;
          list[i].children = this.getNavData(list, list[i].id);
          list[i].codes = list[i].timeTypeCode
            ? list[i].code + "_" + list[i].timeTypeCode
            : "id_" + list[i].id;
          result.push(list[i]);
        }
      }
      return result;
    },

    output() {
      let { exporttype, username, exportRestrictions } = this.userInfo
      if (!exporttype) {
        this.$message({
          message: '试用账号，无此权限！请联系管理员！',
          type: 'warning',
          showClose: true,
          duration: 3000,
          center: true
        });
        return
      }

      if (exportRestrictions) {
        // 查看权限下的导出条数
        this.$axios.request({
          url: "5100/user/exportRestrictions",
          method: "get",
          params: {
            exportNumber: 0,
            userName: username
          },
        }).then(res => {
          let Rpieces = res.data
          if (Rpieces == 0) {
            this.$message({
              message: '试用账号，导出已达上限！',
              type: 'warning',
              showClose: true,
              duration: 3000,
              center: true
            });
            return
          } else {
            // 拷贝原有数据
            let original = JSON.parse(JSON.stringify(this.tableDataff));
            if (this.tableDataff.length > Rpieces) {
              let extract = this.tableDataff.slice(0, Rpieces);
              let Controlcol = this.ReservedBar(extract)
              this.tableDataff = Controlcol
              this.$nextTick(() => {
                this.QuickPass()
                this.Exportsuccess(Rpieces, username)
              })
            } else {
              let Controlcol = this.ReservedBar(this.tableDataff)
              this.tableData = Controlcol
              this.$nextTick(() => {
                this.QuickPass()
                this.Exportsuccess(this.tableDataff.length, username)
              })
            }
            // 还原原有数据
            setTimeout(() => {
              this.tableDataff = original
            })
          }
        })
      } else {
        this.QuickPass()
      }
    },

    // 横向保留20条
    ReservedBar(arr) {
      let newArr = arr.map(obj => {
        let newObj = {}
        let count = 0
        for (let key in obj) {
          if (count < 22) {
            newObj[key] = obj[key];
            count++;
          }
        }
        return newObj
      })
      return newArr
    },

    // 快速导出
    QuickPass() {
      this.statisticType = "3";
      this.statistic();
      var excelName = $(".excelName").html();
      var tdLength = $("#tableDetailData")
        .children(".el-table__body-wrapper")
        .find("tbody")
        .find("tr:first-child td").length;
      var addFooterHtml =
        '<tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"></tr><tr class="tableNone"><td></td><td>数据来源：数据圈</td></tr><tr class="tableNone"><td></td><td>联系人：刘老师</td></tr><tr class="tableNone"><td></td><td>电&nbsp;&nbsp;话：18810308405</td></tr><tr class="tableNone"><td></td><td>E-mail：shicong.liu@shujuquan.com</td></tr>';
      $("#tableDetailData")
        .find(".el-table__fixed-body-wrapper")
        .find("tbody")
        .append(addFooterHtml);
      var wb;
      var fix = document.querySelector(".el-table__fixed");
      if (fix) {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#tableDetailData").removeChild(fix)
        );
        document.querySelector("#tableDetailData").appendChild(fix);
        $(".tableNone").remove();
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#tableDetailData"));
      }
      //var wb = XLSX.utils.table_to_book(document.querySelector("#mydialogtable")); //mydialogtable为表格的id名
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      let date = new Date();
      date = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`;
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          `` + excelName + `${date}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },

    // 导出成功
    Exportsuccess(value, user) {
      this.$axios.request({
        url: "5100/user/exportRestrictions",
        method: "get",
        params: {
          exportNumber: value,
          userName: user
        },
      }).then(res => {
        return res.data
      })
    },

    downloadImpByChart() {
      this.statisticType = "12";
      this.statistic();
      this.picName = $(".excelName").html();
      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等

      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      var this1 = this;
      setTimeout(function () {
        html2canvas(this1.$refs.imageWrapper, {
          backgroundColor: null,
          useCORS: true,
        }).then((canvas) => {
          let dataURL = canvas.toDataURL("image/png");
          this1.downImg = dataURL;
          setTimeout(function () {
            var el = document.getElementById("downImg");
            el.click();
          }, 2000);
        });
      }, 500);
    },

    toImgPrint() { // 转图片打印

      html2canvas(document.querySelector("#app"), {
        backgroundColor: '#25262E',
        useCORS: true,
        windowHeight: document.body.scrollHeight

      }).then((canvas) => {

        // let url = canvas.toDataURL('image/jpeg', 1.0)
        const url = canvas.toDataURL()
        this.img = url

        printJS({
          printable: url,
          type: 'image',
          documentTitle: '打印图片',
          style: `@media print { @page {size: auto; margin: 50px; } body{margin:0px 50px}}`
        })

      })
    },
    print() {
      this.statisticType = "11";
      this.statistic();
      const loading = this.$loading({
        lock: true,
        text: "正在打印...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.toImgPrint();
      loading.close();
    },

    // 递归获取 省市区数组
    getTreeMenuData(arr, parentId) {
      let resultArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (parentId == arr[i].parenid) {
          arr[i].children = this.getTreeMenuData(arr, arr[i].id);
          resultArr.push(arr[i]);
        }
      }
      return resultArr;
    },

    setTimeTrees(res, result) {
      if (!result || result.time === "1") {
        let timeArr = [];
        for (let e of res.data) {
          timeArr.push({
            id: e,
            label: e,
          });
        }
        this.dataTime = [
          {
            id: 3,
            label: "全选",
            children: timeArr,
          },
        ];
      } else if (result.time === "2") {
        let map = new Map();
        let timeArr = [];
        for (let e of res.data) {
          let year = e.substring(0, 4);
          let value = map.get(year) || [];
          value.push({
            id: e,
            label: e,
          });
          map.set(year, value);
        }
        for (let e of map) {
          let key = e[0];
          let value = e[1];
          timeArr.push({
            id: "id_" + key,
            label: key,
            children: value,
          });
        }

        this.dataTime = [
          {
            id: 3,
            label: "全选",
            children: timeArr,
          },
        ];
      }
    },

    statistic() {
      this.$axios
        .request({
          url: "5100/users-anon/statistic",
          method: "post",
          params: {
            access_token: this.token,
          },
          data: {
            username: this.token,
            type: this.statisticType,
            cnt: 1,
            page: this.$route.query.tablename,
            code: this.getIndex.join(","),
          },
        })
        .then((res) => { })
        .catch(function (error) {
          console.log(error);
        });
    },

    prev() {
      if (this.mapYearsNum < 0) {
        this.mapYearsNum += 1;
      }
    },

    setRegionTrees(res, result) {
      if (!result || result.area === "1") {
        // 只显示省
        this.dataRegion[0].children = res.data;
      } else if (result.area === "0") {
        // 全国
        this.dataRegion[0].children = [];
      } else {
        let arr = this.getTreeMenuData(res.data, 0);
        this.dataRegion[0].children = arr;
      }
    },

    anaDataClose() {
      document.getElementById("anaData").innerHTML = "";
      this.anaDataShow = false;
    },

    next() {
      let len = this.mapYears.length;
      if (len <= 8) return;
      if (len - 8 !== Math.abs(this.mapYearsNum)) {
        this.mapYearsNum -= 1;
      }
    },

    websingletableGetData() {
      // 默认 查看条件
      var that = this;
      var params = new URLSearchParams();
      params.append("tableName", that.tableName);
      return new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/getTechData",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.sourceData = res.data;
            that.defaultData = res.data; // 默认数值
            that.dynamiclist(); // 处理默认表头
            that.termlook();
            that.legendClick()
            that.gettable()
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
          });
      });
    },

    handleCheckedGetRegionChange() {
      if (this.isVisibleAreaTab)
        this.$refs.treeRegion.setCheckedKeys(this.getRegion);
    },

    handleClick(tab, event) { },

    conditionsClose() {
      this.mainPositionWinShow = false;
      this.conditionsClear();
      this.termlook();
      setTimeout(() => {
        this.mainPositionWinShow = false;
      });
    },

    nodeClickHandleRegion(data) {
      this.mainPositionWinShow = true;
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.label ? data.label.indexOf(value) !== -1 : false;
    },
    filterNodeclounm(value, datacloumns) {
      if (!value) return true;
      return datacloumns.label ? datacloumns.label.indexOf(value) !== -1 : false;
    },
    filterNodeTime(value, dataTime, node) {
      if (!value) return true;
      return dataTime.label ? value.indexOf(dataTime.label) !== -1 : false;
    },
    filterNodeRegion(value, dataRegion) {
      if (!value) return true;
      return dataRegion.codename
        ? dataRegion.codename.indexOf(value) !== -1
        : false;
    },

    nodeClickHandleTime(data) {
      this.mainPositionWinShow = true;
    },

    filterTextTimeClear() {
      this.filterTextTime = "";
    },

    handleCheckedGetTimeChange() {
      this.$refs.treeTime.setCheckedKeys(this.getTime);
    },

    timeFilterSelectFn(val) {
      //TODO 修改 时间选择器数据
      this.timeFilterSelectVal = val.label;
      this.$refs.treeTime.setCheckedKeys(this.timeSource.slice(0, val.value));
      // val.value  todo 筛选年份
      // debugger
      // let value =
      //   val.value === "全部"
      //     ? ""
      //     : this.timeSource.slice(0, val.value).join(",");
      // this.$refs.treeTime.filter(value);
    },

    viewConditions() {
      let { sourceData } = this;
      let getIndex = [];
      let getRegion = [];
      let getTime = [];
      let getCloumns = JSON.parse(localStorage.getItem('Cloumnslog'));
      for (let key in sourceData) {
        getIndex.push(key.split("|")[0]);
        let item1 = sourceData[key];
        for (let key1 in item1) {
          let region = key1.split("|")[0];
          if (getRegion.indexOf(region) < 0) {
            getRegion.push(region);
          }
          let item2 = item1[key1];
          for (let key2 in item2) {
            if (getTime.indexOf(key2) < 0) {
              getTime.push(key2);
            }
          }
        }
      }
      return {
        getIndex,
        getRegion,
        getTime,
        getCloumns
      };
    },

    predict() {
      this.predictWin = true;
      this.analysisWin = false;
      this.statisticalWin = false;

      this.cur = 0;
      this.graphShow = true;
      this.statementShow = true;
    },

    conditionsClear() {
      this.getCloumns = [];
      this.getCloumnss = [];
      this.$refs.treeCloumns.setCheckedKeys([]);
      this.getIndex = [];
      this.getIndexs = [];
      this.$refs.tree.setCheckedKeys([]);
      this.getTime = [];
      this.getTimes = [];
      this.$refs.treeTime.setCheckedKeys([]);
      this.getRegion = [];
      this.getRegions = [];
      if (this.isVisibleAreaTab) this.$refs.treeRegion.setCheckedKeys([]);
    },

    termlook() {
      window.scrollTo(0, 0);
      this.legendClick()
      let getCloumnsLength = this.getCloumns.length;
      // let getIndexLength = this.getIndex.length;
      let getRegionLength = this.getRegion.length;
      let getTimeLength = this.getTime.length;
      if (getRegionLength == 0 && getTimeLength == 0 && getCloumnsLength == 0) {
        let {  getRegion, getTime, getCloumns } = this.viewConditions();
        this.checkCloumns(null, null, null, getCloumns);
        // this.checkChangeHandle(null, null, null, getIndex);
        this.checkChangeHandleRegion(null, null, null, getRegion);
        this.checkChangeHandleTime(null, null, null, getTime);
      } else {
        this.mainPositionWinShow = true;
      }
    },

    filterTextRegionClear() {
      this.filterTextRegion = "";
    },

    filterTextClear() {
      this.filterText = "";
    },

    anaDataTitleBtn() {
      if (this.anaDataCnt == false) {
        this.anaDataCnt = true;
      } else {
        this.anaDataCnt = false;
      }
    },

    checkCloumns(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys = defaultCheckedKeys || this.$refs.treeCloumns.getCheckedKeys();
      var getCloumnss = [];
      for (var i = 0; i < this.cloumnstree.length; i++) {
        var data1 = this.cloumnstree[i];
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.code) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.code) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                // 有的匹配code
                if (checkedKeys.indexOf(data3.code) >= 0) {
                  // 如果匹配的是 code 用codes替换一下
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(
                      checkedKeys.indexOf(data3.code),
                      1,
                      data3.code
                    );
                  }
                  getCloumnss.push({
                    label: data3.fullname,
                    key: data3.code,
                  });
                }
              }
              // debugger
            } else if (checkedKeys.indexOf(data2.code) >= 0) {
              getCloumnss.push({
                label: data2.fullname,
                key: data2.code,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.code) >= 0) {
          getCloumnss.push({
            label: data1.fullname,
            key: data1.code,
          });
        }
      }

      this.mainPositionWinShow = true;
      this.getCloumns = checkedKeys;
      this.getCloumnss = getCloumnss;
      if (defaultCheckedKeys) {
        this.$refs.treeCloumns.setCheckedKeys(this.getCloumns);
      }
    },

    // checkChangeHandle(data, nodeCheck, childCheck, defaultCheckedKeys) {
    //   var that = this;
    //   var checkedKeys = defaultCheckedKeys || this.$refs.tree.getCheckedKeys();
    //   var getIndexs = [];
    //   for (var i = 0; i < this.data.length; i++) {
    //     var data1 = this.data[i];
    //     if (data1.children && data1.children.length) {
    //       if (checkedKeys.indexOf(data1.codes) >= 0) {
    //         checkedKeys.splice(checkedKeys.indexOf(data1.codes), 1);
    //       }
    //       for (var j = 0; j < data1.children.length; j++) {
    //         var data2 = data1.children[j];
    //         if (data2.children && data2.children.length) {
    //           if (checkedKeys.indexOf(data2.codes) >= 0) {
    //             checkedKeys.splice(checkedKeys.indexOf(data2.codes), 1);
    //           }
    //           for (var k = 0; k < data2.children.length; k++) {
    //             var data3 = data2.children[k];
    //             // 有的匹配code
    //             if (
    //               checkedKeys.indexOf(data3.codes) >= 0 ||
    //               checkedKeys.indexOf(data3.code) >= 0
    //             ) {
    //               // 如果匹配的是 code 用codes替换一下
    //               if (checkedKeys.indexOf(data3.code) >= 0) {
    //                 checkedKeys.splice(
    //                   checkedKeys.indexOf(data3.code),
    //                   1,
    //                   data3.codes
    //                 );
    //               }
    //               getIndexs.push({
    //                 // label: data3.name,
    //                 label: data3.fullname,
    //                 key: data3.codes,
    //               });
    //             }
    //           }
    //           // debugger
    //         } else if (checkedKeys.indexOf(data2.codes) >= 0) {
    //           getIndexs.push({
    //             // label: data2.name,
    //             label: data2.fullname,
    //             key: data2.codes,
    //           });
    //         }
    //       }
    //     } else if (checkedKeys.indexOf(data1.codes) >= 0) {
    //       getIndexs.push({
    //         // label: data1.name,
    //         label: data1.fullname,
    //         key: data1.codes,
    //       });
    //     }
    //   }

    //   this.mainPositionWinShow = true;
    //   this.getIndex = checkedKeys;
    //   this.getIndexs = getIndexs;
    //   // if (defaultCheckedKeys) {
    //   //   this.$refs.tree.setCheckedKeys(this.getIndex);
    //   // }
    // },

    checkChangeHandleRegion(data, nodeCheck, childCheck, defaultCheckedKeys) {
      // 隐藏这个节点的时候返回
      if (!this.isVisibleAreaTab) {
        return;
      }
      var that = this;
      if (this.isVisibleAreaTab) {
        var checkedKeys =
          defaultCheckedKeys || this.$refs.treeRegion.getCheckedKeys();
      } else {
        var checkedKeys = defaultCheckedKeys || [];
      }

      var getRegions = [];
      for (var i = 0; i < this.dataRegion.length; i++) {
        var data1 = this.dataRegion[i];
        //data1
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.code) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.code), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            //data2
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.code) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.code), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                //data3
                // if (checkedKeys.indexOf(data3.code) >= 0) {
                //   getRegions.push({
                //     label: data3.codename,
                //     key: data3.code,
                //   });
                // }
                if (data3.children && data3.children.length) {
                  if (checkedKeys.indexOf(data3.code) >= 0) {
                    checkedKeys.splice(checkedKeys.indexOf(data3.code), 1);
                  }
                  for (var o = 0; o < data3.children.length; o++) {
                    var data4 = data3.children[o];
                    //data4
                    if (checkedKeys.indexOf(data4.code) >= 0) {
                      getRegions.push({
                        label: data4.codename,
                        key: data4.code,
                      });
                    }
                  }
                } else if (checkedKeys.indexOf(data3.code) >= 0) {
                  getRegions.push({
                    label: data3.codename,
                    key: data3.code,
                  });
                }
              }
            } else if (checkedKeys.indexOf(data2.code) >= 0) {
              getRegions.push({
                label: data2.codename,
                key: data2.code,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.code) >= 0) {
          getRegions.push({
            label: data1.codename,
            key: data1.code,
          });
        }
      }
      this.mainPositionWinShow = true;
      this.getRegion = checkedKeys;
      getRegions.sort((a, b) => {
        return Number(a.key) - Number(b.key);
      });
      this.getRegions = getRegions;
      if (defaultCheckedKeys) {
        if (this.isVisibleAreaTab)
          this.$refs.treeRegion.setCheckedKeys(this.getRegion);
      }
      let getIndexLength = this.getIndex.length;
      let getRegionLength = this.getRegion.length;
      let getTimeLength = this.getTime.length;
      if (
        !defaultCheckedKeys &&
        getRegionLength == 1 &&
        getIndexLength == 0 &&
        getTimeLength == 0
      ) {
        let getIndex = [];
        for (var i = 0; i < 5; i++) {
          if (this.data[0].children[0].children.length > i) {
            getIndex.push(this.data[0].children[0].children[i].codes);
          }
        }
        //this.checkChangeHandle(null, null, null, getIndex);
      }
      if (
        !defaultCheckedKeys &&
        getRegionLength == 1 &&
        getIndexLength == 0 &&
        getTimeLength == 0
      ) {
        let getTime = [];
        for (var i = 0; i < 5; i++) {
          if (this.dataTime[0].children.length > i) {
            getTime.push(this.dataTime[0].children[i].id);
          }
        }
        //this.checkChangeHandleTime(null, null, null, getTime);
      }
    },

    // handleCheckedGetIndexChange() {
    //   this.$refs.tree.setCheckedKeys(this.getIndex);
    // },

    handleCheckedGetCloumnsChange() {
      this.$refs.treeCloumns.setCheckedKeys(this.getCloumns);
    },

    checkChangeHandleTime(data, nodeCheck, childCheck, defaultCheckedKeys) {
      var that = this;
      var checkedKeys =
        defaultCheckedKeys || this.$refs.treeTime.getCheckedKeys();
      var getTimes = [];
      for (var i = 0; i < this.dataTime.length; i++) {
        var data1 = this.dataTime[i];
        if (data1.children && data1.children.length) {
          if (checkedKeys.indexOf(data1.id) >= 0) {
            checkedKeys.splice(checkedKeys.indexOf(data1.id), 1);
          }
          for (var j = 0; j < data1.children.length; j++) {
            var data2 = data1.children[j];
            if (data2.children && data2.children.length) {
              if (checkedKeys.indexOf(data2.id) >= 0) {
                checkedKeys.splice(checkedKeys.indexOf(data2.id), 1);
              }
              for (var k = 0; k < data2.children.length; k++) {
                var data3 = data2.children[k];
                if (checkedKeys.indexOf(data3.id) >= 0) {
                  getTimes.push({
                    label: data3.label,
                    key: data3.id,
                  });
                }
              }
            } else if (checkedKeys.indexOf(data2.id) >= 0) {
              getTimes.push({
                label: data2.label,
                key: data2.id,
              });
            }
          }
        } else if (checkedKeys.indexOf(data1.id) >= 0) {
          getTimes.push({
            label: data1.label,
            key: data1.id,
          });
        }
      }
      this.mainPositionWinShow = true;
      this.getTime = checkedKeys;

      this.getTimes = getTimes;
      if (defaultCheckedKeys) {
        this.$refs.treeTime.setCheckedKeys(this.getTime);
      }
      let getIndexLength = this.getIndex.length;
      let getRegionLength = this.getRegion.length;
      let getTimeLength = this.getTime.length;
      if (
        !defaultCheckedKeys &&
        getTimeLength == 1 &&
        getIndexLength == 0 &&
        getRegionLength == 0
      ) {
        let getIndex = [];
        for (var i = 0; i < 5; i++) {
          if (this.data[0].children[0].children.length > i) {
            getIndex.push(this.data[0].children[0].children[i].codes);
          }
        }
        //this.checkChangeHandle(null, null, null, getIndex);
      }
      if (
        !defaultCheckedKeys &&
        getTimeLength == 1 &&
        getIndexLength == 0 &&
        getRegionLength == 0
      ) {
        let getRegion = [];
        for (var i = 0; i < 5; i++) {
          if (this.dataRegion[0].children.length > i) {
            getRegion.push(this.dataRegion[0].children[i].code);
          }
        }
        //this.checkChangeHandleRegion(null, null, null, getRegion);
      }
    },

    termSubmit() {
      const loading = this.$loading({
        lock: true,
        text: "正在提取数据...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.filteratetable()
      this.mainPositionWinShow = false;
      var checkedKey = [];
      var checkedKeycliumn = this.$refs.treeCloumns.getCheckedKeys();
      var checkedKeyRegion = this.$refs.treeRegion.getCheckedKeys();
      var checkedKeyTime = this.$refs.treeTime.getCheckedKeys();
      // var that = this;
      var params = new URLSearchParams();
      let fn = (checkedKey) => {
        var codes = [];
        if (!!checkedKey.length) {
          for (var i = 0; i < checkedKey.length; i++) {
            if (/^id/.test(checkedKey[i])) {
              continue;
            }
            codes.push(checkedKey[i]);
          }
        }
        return codes;
      };
      let codes = fn(checkedKey);
      let regions = [...new Set(fn(checkedKeyRegion))];
      let times = fn(checkedKeyTime);
      let cloumns = fn(checkedKeycliumn);
      let that = this;
      if ( times.length == 0) {
        this.websingletableGetData()
        loading.close();
      } else {
        if (this.tableName.indexOf("global_") != -1) {
          checkedKeyRegion = ["000"];
        }
        if (codes.length !== 0) {
          params.append("codes", codes.join());
        } else {
          params.append("codes", this.getDefualtMenu("getIndex").join());
        }
        if (regions.length !== 0) {
          params.append("regions", regions.join());
        } else {
          params.append("regions", this.getDefualtMenu("getRegion").join());
        }
        if (times.length !== 0) {
          params.append("times", times.join());
        } else {
          params.append("times", this.getDefualtMenu("getTime").join());
        }
        // if(cloumns.length !== 0) {
        params.append("cloumns", '01_0101');
        // } else {
        //   params.append("cloumns", this.getDefualtMenu("getCloumns").join());
        // }
        params.append("tableName", this.tableName);
        this.$axios
          .request({
            url: "5700/websingletable/findTechData",
            method: "post",
            data: params,
          })
          .then(function (res) {
            if (!res.data) {
              alert("此条件下无对应数据");
            }
            that.defaultData = res.data;
            that.sourceData = res.data;
            that.legendClick();
          })
          .catch(function (error) {
            console.log(error);
          })
          .finally(() => {
            loading.close();
          });
        this.gettable()
        this.statisticType = "4";
        this.statistic();
      }
    },

    getDefualtMenu(methodName) {
      let fn = (arr, pushKey) => {
        let result = [];
        for (var i = 0; i < arr.length; i++) {
          if (result.length >= 5) break;
          if (arr[i].children && !!arr[i].children.length) {
            result = fn(arr[i].children, pushKey);
          } else {
            if (_.get(arr[i], pushKey, ""))
              result.push(_.get(arr[i], pushKey, ""));
          }
        }
        return result;
      };

      let obj = {
        getIndex: () => {
          return fn(this.data, "codes");
        },
        getRegion: () => {
          return fn(this.dataRegion, "code");
        },
        getTime: () => {
          return fn(this.dataTime, "id");
        },
        getCloumns: () => {
          return fn(this.cloumnstree, "code")
        }
      };
      return obj[methodName]();
    },

    legendClick(e) {
      let index = e == undefined ? '2' : e.name
      this.value = index
      this.chartformat()
      // this.init()
      // if (this.value == '1') {
      //   this.drawindustry()
      //   this.charttitle.text = '2011年 - 2020年全国企业创新趋势'
      // } else 
      if (this.value == '2') {
        this.drawarea()
        this.charttitle.text = '2011年 - 2020年企业创新行业对比'
      } else {
        this.drawtime()
        this.charttitle.text = '2011年 - 2020年企业创新北京天津等6地对比'
      }
    },

    inittable() {
      var that = this;
      var params = new URLSearchParams();
      params.append("page", that.page);
      params.append("limit", that.limit);
      params.append("tableName","tech_innovate_pt_month")
      return new Promise((resolve, reject) => {
        this.$axios
          .request({
            url: "5700/websingletable/findTechCloumnData",
            method: "get",
            params: params,
          })
          .then(function (res) {
            that.tableDataff = res.data.data
            that.total = res.data.count
            resolve(res);
          })
          .catch(function (error) {
            reject(error);
          });
      });
    },

    // 获取列表
    gettable() {
      var that = this;
      var params = new URLSearchParams();
      // var checkedKey = this.$refs.tree.getCheckedKeys();
      var checkedKeyRegion = ["000000"];
      if (that.tableName.indexOf("global_") != -1) {
        checkedKeyRegion = ["000"];
      }
      if (this.isVisibleAreaTab)
        checkedKeyRegion = this.$refs.treeRegion.getCheckedKeys();
      var checkedKeyTime = this.$refs.treeTime.getCheckedKeys();
      var checkedKeycliumn = this.$refs.treeCloumns.getCheckedKeys();
      let fn = (checkedKey) => {
        var codes = [];
        if (!!checkedKey.length) {
          for (var i = 0; i < checkedKey.length; i++) {
            if (/^id/.test(checkedKey[i])) {
              continue;
            }
            codes.push(checkedKey[i]);
          }
        }
        return codes;
      };
      // let codes = fn(checkedKey);
      // if (codes.length !== 0) {
      //   params.append("codes", codes.join());
      // } else {
      //   params.append("codes", this.getDefualtMenu("getIndex").join());
      // }
      let regions = [...new Set(fn(checkedKeyRegion))];
      if (regions.length !== 0) {
        params.append("regions", regions.join());
      } else {
        params.append("regions", this.getDefualtMenu("getRegion").join());
      }

      let times = fn(checkedKeyTime);
      if (times.length !== 0) {
        params.append("times", times.join());
      } else {
        params.append("times", this.getDefualtMenu("getTime").join());
      }
      let cloumns = fn(checkedKeycliumn);
      if (cloumns.length !== 0) {
        params.append("cloumns", cloumns.join());
      } else {
        params.append("cloumns", this.getDefualtMenu("getCloumns").join());
      }
      params.append("page", this.page);
      params.append("limit", this.limit);
      params.append("tableName","tech_innovate_pt_month")
      this.$axios.request({
        url: "5700" + "/websingletable/findTechCloumnData",
        method: "post",
        data: params,
      }).then(function (res) {
        that.tableDataff = res.data.data
        that.total = res.data.count
      })
    },

    // 行业
    // drawindustry() {
    //   let { industrydata, legend } = this
    //   var xData = [];
    //   var series = [];
    //   let obj1 = {
    //     name: '',
    //     type: 'bar',
    //     color: '#4992FF',
    //     data: []
    //   }
    //   let obj2 = {
    //     name: '',
    //     type: 'bar',
    //     color: '#7CFEB2',
    //     data: []
    //   }
    //   let obj3 = {
    //     name: '',
    //     type: 'bar',
    //     color: '#FBDD61',
    //     data: []
    //   }
    //   let obj4 = {
    //     name: '',
    //     type: 'bar',
    //     color: '#F66E76',
    //     data: []
    //   }

    //   _.map(industrydata, (o) => {
    //     xData.push(o.name)
    //     _.forEach(o.data, (xd) => {
    //       if (xd.lable == '公司数' && _.indexOf(legend, '公司数') != -1) {
    //         obj1.name = '公司数'
    //         obj1.data.push(xd.value)
    //       }
    //       if (xd.lable == '专利数' && _.indexOf(legend, '专利数') != -1) {
    //         obj2.name = '专利数'
    //         obj2.data.push(xd.value)
    //       }
    //       if (xd.lable == '商标数' && _.indexOf(legend, '商标数') != -1) {
    //         obj3.name = '商标数'
    //         obj3.data.push(xd.value)
    //       }
    //       if (xd.lable == '软著数' && _.indexOf(legend, '软著数') != -1) {
    //         obj4.name = '软著数'
    //         obj4.data.push(xd.value)
    //       }
    //     })
    //   })
    //   series.push(obj1)
    //   series.push(obj2)
    //   series.push(obj3)
    //   series.push(obj4)

    //   var myChart = this.$echarts.init(document.getElementById("myChart"));
    //   var chartOption = {
    //     tooltip: {
    //       trigger: 'axis',
    //       axisPointer: {
    //         type: 'cross',
    //         crossStyle: {
    //           color: '#fff',
    //         },
    //       },
    //     },
    //     legend: {
    //       data: legend,
    //       textStyle: {
    //         color: '#fff',
    //       }
    //     },
    //     xAxis: [{
    //       type: 'category',
    //       data: xData,
    //       axisPointer: {
    //         type: 'shadow',
    //       },
    //       axisLabel: {
    //         show: true,
    //         textStyle: {
    //           color: 'rgba(255, 255, 255,.8)',
    //         }
    //       }
    //     },
    //     ],
    //     yAxis: {
    //       type: 'value',
    //       axisLabel: {
    //         show: true,
    //         textStyle: {
    //           color: 'rgba(255, 255, 255,.8)',
    //         }
    //       }
    //     },
    //     series: series
    //   };
    //   myChart.setOption(chartOption, true);
    // },
    // 地区
    drawarea() {
      this.legend =  ['专利数']
      let { industrydata, legend } = this
      var xData = [];
      var series = [];
      // let obj1 = {
      //   name: '',
      //   type: 'bar',
      //   color: '#4992FF',
      //   data: []
      // }
      let obj2 = {
        name: '',
        type: 'bar',
        color: '#7CFEB2',
        data: []
      }
      // let obj3 = {
      //   name: '',
      //   type: 'bar',
      //   color: '#FBDD61',
      //   data: []
      // }
      // let obj4 = {
      //   name: '',
      //   type: 'bar',
      //   color: '#F66E76',
      //   data: []
      // }

      _.map(industrydata, (o) => {
        xData.push(o.name)
        _.forEach(o.data, (xd) => {
          // if (xd.lable == '公司数' && _.indexOf(legend, '公司数') != -1) {
          //   obj1.name = '公司数'
          //   obj1.data.push(xd.value)
          // }
          if (xd.lable == '专利数' && _.indexOf(legend, '专利数') != -1) {
            obj2.name = '专利数'
            obj2.data.push(xd.value)
          }
          // if (xd.lable == '商标数' && _.indexOf(legend, '商标数') != -1) {
          //   obj3.name = '商标数'
          //   obj3.data.push(xd.value)
          // }
          // if (xd.lable == '软著数' && _.indexOf(legend, '软著数') != -1) {
          //   obj4.name = '软著数'
          //   obj4.data.push(xd.value)
          // }
        })
      })
      // series.push(obj1)
      series.push(obj2)
      // series.push(obj3)
      // series.push(obj4)

      var myChart = this.$echarts.init(document.getElementById("myChart"));
      var chartOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#fff',
            },
          },
        },
        legend: {
          data: legend,
          textStyle: {
            color: '#fff',
          }
        },
        xAxis: [{
          type: 'category',
          data: xData,
          axisPointer: {
            type: 'shadow',
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(255, 255, 255,.8)',
            }
          }
        },
        ],
        yAxis: {
          type: 'value',
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(255, 255, 255,.8)',
            }
          }
        },
        series: series
      };
      myChart.setOption(chartOption, true);
    },

    // 时间
    drawtime() {
      this.legend =  ['专利数']
      let { industrydata, legend } = this
      var xData = [];
      var series = [];
      // let obj1 = {
      //   name: '',
      //   type: 'line',
      //   color: '#4992FF',
      //   data: []
      // }
      let obj2 = {
        name: '',
        type: 'line',
        color: '#7CFEB2',
        data: []
      }
      // let obj3 = {
      //   name: '',
      //   type: 'line',
      //   color: '#FBDD61',
      //   data: []
      // }
      // let obj4 = {
      //   name: '',
      //   type: 'line',
      //   color: '#F66E76',
      //   data: []
      // }

      _.map(industrydata.reverse(), (o) => {
        xData.push(o.name)
        _.forEach(o.data, (xd) => {
          // if (xd.lable == '公司数' && _.indexOf(legend, '公司数') != -1) {
          //   obj1.name = '公司数'
          //   obj1.data.push(xd.value)
          // }
          if (xd.lable == '专利数' && _.indexOf(legend, '专利数') != -1) {
            obj2.name = '专利数'
            obj2.data.push(xd.value)
          }
          // if (xd.lable == '商标数' && _.indexOf(legend, '商标数') != -1) {
          //   obj3.name = '商标数'
          //   obj3.data.push(xd.value)
          // }
          // if (xd.lable == '软著数' && _.indexOf(legend, '软著数') != -1) {
          //   obj4.name = '软著数'
          //   obj4.data.push(xd.value)
          // }
        })
      })
      // series.push(obj1)
      series.push(obj2)
      // series.push(obj3)
      // series.push(obj4)
      var myChart = this.$echarts.init(document.getElementById("myChart"));
      var chartOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#fff',
            },
          },
        },
        legend: {
          data: legend,
          textStyle: {
            color: '#fff',
          }
        },
        xAxis: [{
          type: 'category',
          data: xData,
          axisPointer: {
            type: 'shadow',
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(255, 255, 255,.8)',
            }
          }
        },
        ],
        yAxis: {
          type: 'value',
          axisLabel: {
            show: true,
            textStyle: {
              color: 'rgba(255, 255, 255,.8)',
            }
          }
        },
        series: series
      };
      myChart.setOption(chartOption, true);
    }
  }
}
</script>

<style lang="less" scoped>
.tree {
  overflow-y: auto;
  overflow-x: auto;
  /* width: 80px; */
  height: 800px;
}

/deep/ .table-l {
  position: relative;
}

/deep/ .el-table__body-wrapper {
  border-top: 0 !important;
}

/deep/ .el-table__fixed-right::before,
.el-table__fixed::before {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #1f2027;
  z-index: 4;
}

.timeSelect {
  width: 64%;
  color: rgb(255, 255, 255);
  background: #25262e;
  height: 30px;
  line-height: 30px;
  padding-left: 10%;
}

.inputBlack input {
  background: #fff;
  color: #000;
}

.indexCodePopBox {
  .predictWin {
    top: 25%;
  }

  .indexCodePop {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  ul {
    background: #25262e;
    box-shadow: #000;

    li {
      display: flex;

      div {
        flex: 1;
        padding: 10px;
      }

      div:first-child {
        border-right: 1px solid #4b4c53;
      }
    }

    li:not(:last-child) {
      border-bottom: 1px solid #4b4c53;
    }
  }
}

.mainMap {
  position: relative;

  .mapYears {
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);

    .mapIcon1 {
      position: absolute;
      right: 2px;
      top: -17px;
      width: 18px;
      padding: 0 10px;
    }

    .mapIcon2 {
      position: absolute;
      right: 2px;
      bottom: -17px;
      width: 18px;
      padding: 0 10px;
    }

    ul {
      li {
        position: relative;
        height: 60px;
        display: flex;
        align-items: center;
        padding-right: 30px;

        .mapIcon {
          width: 20px;
          height: 20px;
          margin-left: 10px;
          z-index: 99;
          position: absolute;
          right: 0;
          background: #25262e;
          padding: 5px 0;
        }

        .mapIconActive {
          width: 26px;
          height: 26px;
          right: -3px;
        }

        .mapYears-line {
          position: absolute;
          right: 10px;
          width: 1px;
          height: 100%;
          background: #fff;
          top: 0px;
          z-index: 88;
        }
      }
    }
  }
}

/deep/ .el-tabs--card > .el-tabs__header .el-tabs__item {
  text-align: center;
}

/deep/ .el-table thead.is-group th.el-table__cell {
  background: #25262e;
}
</style>